/**
 * @description 系统配置
 *
 * @author xiaomi
 */

const passport = require('passport');

module.exports = function(app) {
    const apiRouter = app.apiRouter;
    const Config = app.models.Config;

    // apiRouter.get('/config', passport.authorized(), function *() {
    //     this.body = {
    //         app: yield Config.getConfig('app'),
    //         'email-config': yield Config.getConfig('email-config'),
    //     };
    // });

    apiRouter.post('/config', function *() {
        const body = this.request.body;
        this.body = {
            app: yield Config.setConfig('app', body.app),
            'email-config': yield Config.setConfig('email-config', body['email-config'])
        };
    });

     // 修改配置
    apiRouter.put('/config/:type', function * () {
        const typesMap = Config.typesMap;
        const type = this.params.type;
        const user = this.req.user;

        if(!typesMap[type]) {
            this.throw(404, '配置类型未找到：' + type);
        }

        const body = this.request.body;
        const data = {};

        // Drop it with start $
        Object.keys(body).forEach(k => {
            if(k && k.indexOf('$') !== 0) {
                data[k] = body[k];
            }
        });

        if(!Object.keys(data).length) {
            this.throw(400, '配置不能为空！');
        }

        this.body = yield Config.setConfig(type, data, {
            manager_id: user.id,
            last_ip: this.ip
        });
    });
};
